﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taurus.Garden.DTO;
using Taurus.Platform.XML;
using System.Xml.Linq;

namespace Taurus.Garden.XML
{
    class SeedPersistence : BasePersistence<Seed>
    {
        public override string FileName
        {
            get { return "Seed.xml"; }
        }

        public override Seed GetObject(string id)
        {
            return XChange(GetEl(new Seed() { ID = id }));
        }

        public override System.Xml.Linq.XElement GetEl(Seed item)
        {
            var t = (from el in Root.Elements("seed") where el.Element("ID").Value == item.ID select el).FirstOrDefault();
            return t;
        }

        protected override System.Xml.Linq.XElement XChange(Seed item)
        {
            XElement el = new XElement("seed",
                new XElement("ID", item.ID),
                new XElement("IsKaiXinBi", item.IsKaiXinBi),
                new XElement("Name", item.Name),
                new XElement("Price", item.Price)
                );
            return el;
        }

        protected override Seed XChange(System.Xml.Linq.XElement item)
        {
            Seed seed = new Seed();
            seed.IsKaiXinBi = bool.Parse(item.Element("IsKaiXinBi").Value);
            seed.Name = item.Element("Name").Value;
            seed.Price = item.Element("Price").Value;
            seed.ID = item.Element("ID").Value;
            return seed;
        }

        public DateTime FileRecordTime(DateTime? time)
        {
            if (time == null)
            {
                if (Root.Attribute("time") == null)
                {
                    //返回昨天的日期，代表要更新
                    return DateTime.Now.AddDays(-1);
                }
                return DateTime.Parse(Root.Attribute("time").Value);
            }
            else
            {
                Root.SetAttributeValue("time",time.Value.ToString());
                return time.Value;
            }
        }
        
    }
}
